package com.android.baseconfig.common.views;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.baseconfig.R;
import com.android.baseconfig.common.utils.StringUtils;

/**
 * @author lei
 * @description 自定义全局标准对话框
 * @date 2018/5/5
 */
public class AppBasicDialog extends Dialog {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusTextColorDark(this);
    }

    public static void setStatusTextColorDark(Dialog dialog) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            dialog.getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            dialog.getWindow().setStatusBarColor(Color.BLACK);
        }
    }

    public AppBasicDialog(Context context, int theme) {
        super(context, theme);
    }

    public AppBasicDialog(Context context) {
        super(context);
    }

    public static class Builder {
        private Context context;

        private View contentView;

        private View layout = null;

        private String title;

        private String message;

        private String positiveButtonText;

        private int negativeColor = 0;

        private String negativeButtonText;

        private String feedbackButtonText;

        private Boolean isInput;

        private Boolean edIsPwd = false;

        private int edtTextLength = 32;

        private String editValue;

        /**
         * <p>
         * checkBox框的提示信息
         * </p>
         */
        private String checkTipValue;

        private String hint = "";

        private OnClickListener positiveButtonClickListener;

        private OnClickListener negativeButtonClickListener;

        private OnClickListener feedbackButtonClickListener;

        private Boolean isHintPostivieBtn = false;

        private Boolean hasCheckBox = false;

        private boolean bCheck = true;

        /**
         * 默认底部弹框样式
         */
        private boolean bottomStyle = true;
        /**
         * 默认均分button宽度
         */
        private boolean averageButton = true;
        /**
         * 默认有标题
         */
        private boolean noTitle = false;

        public Builder(Context context, Boolean isInput) {
            this.context = context;
            this.isInput = isInput;
        }

        /**
         * 构造函数<br>
         * <br>
         *
         * @param context     active
         * @param isInput     是否有输入框
         * @param hasCheckBox 是否有勾选框
         * @see [相关类，可选、也可多条，对于重要的类或接口建议注释]
         * @since LinkHome, 2015-8-19
         */
        public Builder(Context context, Boolean isInput, boolean hasCheckBox) {
            this.context = context;
            this.isInput = isInput;
            this.hasCheckBox = hasCheckBox;
        }

        /**
         * @return Returns the isCheck.
         */
        public boolean isbCheck() {
            return bCheck;
        }

        /**
         * @param //isCheck The isCheck to set.
         */
        public void setbCheck(boolean bCheck) {
            this.bCheck = bCheck;
        }

        public void setBottomStyle(boolean bottomStyle) {
            this.bottomStyle = bottomStyle;
        }

        public void setAverageButton(boolean averageButton) {
            this.averageButton = averageButton;
        }

        public void setNoTitle(boolean noTitle) {
            this.noTitle = noTitle;
        }

        public String getEditValue() {
            return editValue;
        }

        public Builder setEditValue(String value) {
            this.editValue = value;
            return this;

        }

        /**
         * @return Returns the checkTipValue.
         */
        public String getCheckTipValue() {
            return checkTipValue;
        }

        /**
         * @param checkTipValue The checkTipValue to set.
         */
        public void setCheckTipValue(String checkTipValue) {
            this.checkTipValue = checkTipValue;
        }

        public Builder setEdIsPwd(boolean flag) {
            edIsPwd = flag;
            return this;
        }

        public Builder setEdtTextLength(int edtTextLength) {
            this.edtTextLength = edtTextLength;
            return this;
        }

        public String getHint() {
            return hint;
        }

        public void setHint(String hint) {
            this.hint = hint;
        }

        public Builder setIsHintPostivieBtn(Boolean flag) {
            this.isHintPostivieBtn = flag;
            return this;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        /**
         * Set the Dialog message from resource
         *
         * @param //title
         * @return
         */
        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }

        /**
         * Set the Dialog title from resource
         *
         * @param title
         * @return
         */
        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        /**
         * Set the Dialog title from String
         *
         * @param title
         * @return
         */

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        public Builder setNegativeColor(int color) {
            this.negativeColor = color;
            return this;
        }

        /**
         * Set the positive button resource and it's listener
         *
         * @param positiveButtonText
         * @return
         */
        public Builder setPositiveButton(int positiveButtonText, OnClickListener listener) {
            this.positiveButtonText = (String) context.getText(positiveButtonText);
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText, OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText, OnClickListener listener) {
            this.negativeButtonText = (String) context.getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String negativeButtonText, OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setFeedbackButton(int feedbackButtonText, OnClickListener listener) {
            this.feedbackButtonText = context.getString(feedbackButtonText);
            this.feedbackButtonClickListener = listener;
            return this;
        }

        public AppBasicDialog create() {
            LayoutInflater inflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // instantiate the dialog with the custom Theme
            final AppBasicDialog dialog = new AppBasicDialog(context, R.style.appBasicDialog);
            WindowManager m = ((Activity) context).getWindowManager();
            Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
            Point point = new Point();
            d.getSize(point);
            android.view.WindowManager.LayoutParams params =
                    dialog.getWindow().getAttributes();  //获取对话框当前的参数值、
            Button positiveBtn;
            Button negativeBtn;
            if (!bottomStyle) {
                layout = inflater.inflate(R.layout.dialog_app_basic, null);
                dialog.addContentView(layout, new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));

                params.width = (int) (point.x * 0.76);    //宽度设置全屏宽度
                dialog.getWindow().setAttributes(params);     //设置生效
                // AppBasicDialog.setStatusTextColorDark(dialog);

                positiveBtn = layout.findViewById(R.id.positive_btn);
                negativeBtn = layout.findViewById(R.id.negative_btn);
                if (positiveButtonText != null && negativeButtonText == null) {
                    positiveBtn.setBackgroundResource(R.drawable.bg_basicdialog_right_left_btn);
                } else if (positiveButtonText == null && negativeButtonText != null) {
                    negativeBtn.setBackgroundResource(R.drawable.bg_basicdialog_right_left_btn);
                }
            } else {
                layout = inflater.inflate(R.layout.dialog_app_basic_bottom, null);
                dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT));

                params.width = (int) (point.x);    //宽度设置全屏宽度
                dialog.getWindow().setAttributes(params);     //设置生效
                dialog.getWindow().setGravity(Gravity.BOTTOM);
                dialog.getWindow().setWindowAnimations(R.style.bottom_window_anim);

                positiveBtn = layout.findViewById(R.id.positive_btn);
                negativeBtn = layout.findViewById(R.id.negative_btn);
                if (!averageButton) {
                    LinearLayout.LayoutParams positiveBtnLayoutParams = (LinearLayout.LayoutParams) positiveBtn.getLayoutParams();
                    positiveBtnLayoutParams.weight = 2.4f;
                    positiveBtn.setLayoutParams(positiveBtnLayoutParams);
                }
            }

            // set the dialog title
            TextView titleText = ((TextView) layout.findViewById(R.id.dialog_title));
            if (!StringUtils.isEmpty(title)) {
                titleText.setText(title);
            } else {
                if (noTitle) {
                    titleText.setVisibility(View.GONE);
                }
            }

            final EditText inputText = ((EditText) layout.findViewById(R.id.dialog_edit));

            inputText.setText(editValue);

            if (edIsPwd) {
                inputText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }

            inputText.setHint(getHint());

            inputText.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        inputText.setHint("");
                    } else {
                        inputText.setHint(getHint());
                    }

                }
            });

            CheckBox checkBox = ((CheckBox) layout.findViewById(R.id.dialog_checkBox));
            checkBox.setVisibility(View.GONE);
            layout.findViewById(R.id.checkBoxDisc).setVisibility(View.GONE);
            layout.findViewById(R.id.dialog_checkBox_line).setVisibility(View.GONE);
            if (hasCheckBox && !StringUtils.isEmpty(checkTipValue)) {
                ((TextView) layout.findViewById(R.id.checkBoxDisc)).setText(checkTipValue);
                layout.findViewById(R.id.dialog_checkBox_line).setVisibility(View.VISIBLE);
                layout.findViewById(R.id.checkBoxDisc).setVisibility(View.VISIBLE);
                checkBox.setVisibility(View.VISIBLE);
            }

            if (!isInput) {
                layout.findViewById(R.id.dialog_edit).setVisibility(View.GONE);
            } else {
                layout.findViewById(R.id.cont_layout).setPadding(20, 0, 20, 20);
            }

            if (edtTextLength > 0) {
                inputText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(edtTextLength)});
            }

            View confirmView = layout.findViewById(R.id.ll_confirm);
            // set the confirm button
            if (positiveButtonText != null) {
                positiveBtn.setText(positiveButtonText);
                if (positiveButtonClickListener != null) {
                    positiveBtn.setOnClickListener(v -> {
                        if (isInput) {
                            editValue = inputText.getText().toString();
                        }
                        if (hasCheckBox && !StringUtils.isEmpty(checkTipValue)) {
                            bCheck =
                                    ((CheckBox) layout.findViewById(R.id.dialog_checkBox)).isChecked();
                        }
                        positiveButtonClickListener.onClick(dialog,
                                DialogInterface.BUTTON_POSITIVE);
                    });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                positiveBtn.setVisibility(View.GONE);
                layout.findViewById(R.id.btn_vertical_line).setVisibility(View.GONE);
                confirmView.setPadding(context.getResources().getDimensionPixelSize(R.dimen.dp_31),
                        confirmView.getPaddingTop(),
                        context.getResources().getDimensionPixelSize(R.dimen.dp_31),
                        confirmView.getPaddingBottom());
            }
            // set the cancel button
            if (negativeButtonText != null) {
                negativeBtn.setText(negativeButtonText);
                if (negativeColor != 0) {
                    negativeBtn.setTextColor(negativeColor);
                }
                if (negativeButtonClickListener != null) {
                    negativeBtn.setOnClickListener(v -> negativeButtonClickListener
                                    .onClick(dialog, DialogInterface.BUTTON_NEGATIVE));
                }
            } else {
                // if no confirm button just set the visibility to GONE
                negativeBtn.setVisibility(View.GONE);
                layout.findViewById(R.id.btn_vertical_line).setVisibility(View.GONE);
                confirmView.setPadding(context.getResources().getDimensionPixelSize(R.dimen.dp_31),
                        confirmView.getPaddingTop(),
                        context.getResources().getDimensionPixelSize(R.dimen.dp_31),
                        confirmView.getPaddingBottom());
            }


            if (!TextUtils.isEmpty(feedbackButtonText)) {
                // 显示中间的按钮
                Button feedback = ((Button) layout.findViewById(R.id.feedback_btn));
                feedback.setText(feedbackButtonText);
                feedback.setVisibility(View.VISIBLE);
                View verticalLine = layout.findViewById(R.id.feedback_vertical_line);
                verticalLine.setVisibility(View.VISIBLE);
                feedback.setOnClickListener(v -> feedbackButtonClickListener.onClick(dialog,
                        DialogInterface.BUTTON_POSITIVE));
            }
            // set the content message
            if (message != null) {
                layout.findViewById(R.id.dialog_info).setVisibility(View.VISIBLE);
                ((TextView) layout.findViewById(R.id.dialog_info)).setText(message);
            } else if (contentView != null) {
                // if no message set
                // add the contentView to the dialog body
                ((LinearLayout) layout.findViewById(R.id.cont_layout)).removeAllViews();
                ((LinearLayout) layout.findViewById(R.id.cont_layout)).addView(contentView,
                        new LayoutParams(
                                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            } else {
                layout.findViewById(R.id.cont_layout).setVisibility(View.GONE);
            }

            if (isHintPostivieBtn) {
                positiveBtn.setVisibility(View.GONE);
                (layout.findViewById(R.id.btn_vertical_line)).setVisibility(View.GONE);
            }
            dialog.setContentView(layout);
            return dialog;
        }

    }

}
